package cn.com.device.monitor.controller;

import cn.com.device.monitor.service.IotdbService;
import cn.com.device.monitor.vo.AjaxResult;
import cn.com.device.monitor.vo.MqttMessgeVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DataController {
    Logger logger = LoggerFactory.getLogger(DataController.class);
    @Autowired
    private IotdbService iotdbService;

    /**
     * 保存数据
     * 一个设备的中所有节点数据同时更新
     * @param {"deviceId":"sb0001","temperature":"24","warn":"false","status":"run"}
     * code的值不能有下划线
     * @return
     */
    @PostMapping("/insert")
    public AjaxResult insertData(@RequestBody MqttMessgeVO data) {
        try {
            iotdbService.save(data);
            return AjaxResult.success("success");
        } catch (Exception e) {
            logger.error("保存异常",e);
            return AjaxResult.error("保存异常",e);
        }
    }

    /**
     * 查询设备最新检测数据
     * @param deviceId
     * @return
     */
    @GetMapping("/query")
    public AjaxResult queryData(@RequestParam("deviceId") String deviceId) {
        try {
            // root.hsd.paper.device01
            List<MqttMessgeVO> records = iotdbService.queryData(deviceId);
            // 处理查询结果
            return AjaxResult.success(records);
        } catch (Exception e) {
            logger.error("删除异常",e);
            return AjaxResult.error("删除异常",e);
        }
    }

    /**
     * 获取所有设备的最新数据
     * 条件：单个设备中所欲节点数据必须要同时更新，这样查询出来才都是所有节点最新数据
     * http://localhost:9081/device-monitor/query?deviceId=sb0001
     * @return
     */
    @GetMapping("/queryLastData")
    public AjaxResult queryLastData() {
        try {
            List<MqttMessgeVO> records = iotdbService.queryLastData();
            // 处理查询结果
            return AjaxResult.success(records);
        } catch (Exception e) {
            logger.error("获取所有设备的最新数据异常",e);
            return AjaxResult.error("获取所有设备的最新数据异常",e);
        }
    }
}
